<template>
  <nav class="navbar navbar-expand-lg navbar-light fixed-top" :class="navbarClass">
    <div class="container">
      <!-- Logo/品牌 -->
      <router-link class="navbar-brand fw-bold" to="/">
        <img 
          :src="require('@/assets/log.png')" 
          alt="Logo" 
          height="40"
          class="d-inline-block align-text-top me-2"
        >
        <span class="brand-text">我的博客</span>
      </router-link>

      <!-- 移动端汉堡菜单按钮 -->
      <button 
        class="navbar-toggler border-0" 
        type="button" 
        data-bs-toggle="collapse" 
        data-bs-target="#navbarNav"
        :class="{ 'navbar-toggler-white': isScrolled }"
      >
        <span class="navbar-toggler-icon"></span>
      </button>

      <!-- 导航菜单 -->
      <div class="collapse navbar-collapse" id="navbarNav">
        <ul class="navbar-nav ms-auto">
          <li class="nav-item">
            <router-link 
              class="nav-link px-3" 
              to="/"
              :class="{ active: $route.name === 'Home' }"
            >
              <i class="bi bi-house me-1"></i>首页
            </router-link>
          </li>
          <li class="nav-item">
            <router-link 
              class="nav-link px-3" 
              to="/blog"
              :class="{ active: $route.name === 'Blog' }"
            >
              <i class="bi bi-journal-text me-1"></i>文章
            </router-link>
          </li>
          <li class="nav-item">
            <router-link 
              class="nav-link px-3" 
              to="/about"
              :class="{ active: $route.name === 'About' }"
            >
              <i class="bi bi-person me-1"></i>关于我
            </router-link>
          </li>
          <li class="nav-item">
            <router-link 
              class="nav-link px-3" 
              to="/contact"
              :class="{ active: $route.name === 'Contact' }"
            >
              <i class="bi bi-envelope me-1"></i>联系
            </router-link>
          </li>
        </ul>

        <!-- 搜索框 -->
        <form class="d-flex ms-lg-3 mt-3 mt-lg-0" @submit.prevent="performSearch">
          <div class="input-group">
            <input 
              class="form-control search-input" 
              type="search" 
              placeholder="搜索..."
              v-model="searchQuery"
            >
            <button class="btn btn-outline-primary" type="submit">
              <i class="bi bi-search"></i>
            </button>
          </div>
        </form>

        <!-- 用户认证和工具 -->
        <div class="navbar-tools ms-3 d-flex align-items-center">
          <!-- 用户菜单 -->
          <div v-if="currentUser" class="dropdown me-2">
            <button 
              class="btn btn-link nav-link border-0 dropdown-toggle d-flex align-items-center" 
              type="button"
              id="userDropdown"
              data-bs-toggle="dropdown"
              aria-expanded="false"
            >
              <i class="bi bi-person-circle me-1"></i>
              <span class="d-none d-md-inline">{{ currentUser.username }}</span>
            </button>
            <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown">
              <li>
                <h6 class="dropdown-header">
                  <i class="bi bi-person me-1"></i>{{ currentUser.username }}
                </h6>
              </li>
              <li><hr class="dropdown-divider"></li>
              <li>
                <a class="dropdown-item" href="#" @click.prevent="">
                  <i class="bi bi-person-gear me-2"></i>个人设置
                </a>
              </li>
              <li>
                <a class="dropdown-item" href="#" @click.prevent="">
                  <i class="bi bi-heart me-2"></i>我的收藏
                </a>
              </li>
              <li><hr class="dropdown-divider"></li>
              <li>
                <a class="dropdown-item text-danger" href="#" @click.prevent="handleLogout">
                  <i class="bi bi-box-arrow-right me-2"></i>退出登录
                </a>
              </li>
            </ul>
          </div>

          <!-- 登录按钮 (未登录时显示) -->
          <router-link 
            v-else
            to="/auth" 
            class="btn btn-outline-primary me-2"
            title="登录/注册"
          >
            <i class="bi bi-person me-1"></i>
            <span class="d-none d-md-inline">登录</span>
          </router-link>

          <!-- 主题切换按钮 -->
          <button 
            class="btn btn-link nav-link border-0 me-2" 
            @click="toggleTheme"
            :title="isDarkTheme ? '切换到亮色主题' : '切换到深色主题'"
          >
            <i class="bi" :class="isDarkTheme ? 'bi-sun' : 'bi-moon'"></i>
          </button>

          <!-- RSS订阅 -->
          <a 
            href="#" 
            class="btn btn-link nav-link border-0 me-2"
            title="RSS订阅"
          >
            <i class="bi bi-rss"></i>
          </a>

          <!-- 返回顶部按钮 -->
          <button 
            class="btn btn-link nav-link border-0" 
            @click="scrollToTop"
            v-show="showBackToTop"
            title="返回顶部"
          >
            <i class="bi bi-arrow-up"></i>
          </button>
        </div>
      </div>
    </div>
  </nav>
</template>

<script>
export default {
  name: 'TheNavbar',
  inject: ['isDarkTheme', 'toggleTheme'],
  data() {
    return {
      isScrolled: false,
      showBackToTop: false,
      searchQuery: '',
      currentUser: null
    }
  },
  computed: {
    navbarClass() {
      return {
        'navbar-scrolled bg-white shadow': this.isScrolled && !this.isDarkTheme,
        'navbar-scrolled bg-dark shadow': this.isScrolled && this.isDarkTheme,
        'navbar-dark': this.isDarkTheme
      }
    }
  },
  mounted() {
    this.handleScroll()
    window.addEventListener('scroll', this.handleScroll)
    this.checkAuthStatus()
    
    // 监听存储变化，以便在其他标签页登录/注销时同步状态
    window.addEventListener('storage', this.handleStorageChange)
  },
  beforeUnmount() {
    window.removeEventListener('scroll', this.handleScroll)
    window.removeEventListener('storage', this.handleStorageChange)
  },
  methods: {
    handleScroll() {
      const scrollTop = window.pageYOffset || document.documentElement.scrollTop
      this.isScrolled = scrollTop > 50
      this.showBackToTop = scrollTop > 300
    },
    scrollToTop() {
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      })
    },
    performSearch() {
      if (this.searchQuery.trim()) {
        this.$router.push({
          path: '/blog',
          query: { search: this.searchQuery }
        })
        this.searchQuery = ''
      }
    },
    
    // 检查用户认证状态
    checkAuthStatus() {
      // 优先检查localStorage，再检查sessionStorage
      let authData = localStorage.getItem('blog_auth')
      if (!authData) {
        authData = sessionStorage.getItem('blog_auth')
      }
      
      if (authData) {
        try {
          const parsedData = JSON.parse(authData)
          this.currentUser = parsedData.user
        } catch (error) {
          console.error('解析认证数据失败:', error)
          this.clearAuthData()
        }
      } else {
        this.currentUser = null
      }
    },
    
    // 处理存储变化事件
    handleStorageChange(event) {
      if (event.key === 'blog_auth') {
        this.checkAuthStatus()
      }
    },
    
    // 处理退出登录
    handleLogout() {
      if (confirm('确定要退出登录吗？')) {
        this.clearAuthData()
        this.currentUser = null
        
        // 显示退出成功消息
        this.$router.push('/').then(() => {
          // 可以在这里添加全局提示组件显示退出成功
          console.log('已退出登录')
        })
      }
    },
    
    // 清除认证数据
    clearAuthData() {
      localStorage.removeItem('blog_auth')
      sessionStorage.removeItem('blog_auth')
    }
  }
}
</script>

<style scoped>
.navbar {
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
  z-index: 1050;
}

.navbar-scrolled {
  background-color: rgba(255, 255, 255, 0.85) !important;
  backdrop-filter: blur(15px);
  border-bottom: 1px solid rgba(0,0,0,0.1);
}

.navbar-brand {
  font-size: 1.5rem;
  color: #0d6efd !important;
  transition: all 0.3s ease;
}

.navbar-brand:hover {
  transform: scale(1.05);
}

.brand-text {
  background: linear-gradient(45deg, #0d6efd, #6f42c1);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.nav-link {
  font-weight: 500;
  transition: all 0.3s ease;
  position: relative;
  border-radius: 0.5rem;
}

.nav-link:hover {
  color: #0d6efd !important;
  transform: translateY(-2px);
}

.nav-link.active {
  color: #0d6efd !important;
  background: rgba(13, 110, 253, 0.1);
}

.nav-link.active::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 50%;
  transform: translateX(-50%);
  width: 30px;
  height: 3px;
  background: #0d6efd;
  border-radius: 2px;
}

.search-input {
  border: 1px solid #dee2e6;
  border-radius: 0.375rem 0 0 0.375rem;
  transition: all 0.3s ease;
}

.search-input:focus {
  border-color: #86b7fe;
  box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
}

.navbar-toggler {
  padding: 0.25rem 0.5rem;
  border-radius: 0.375rem;
}

.navbar-toggler:focus {
  box-shadow: none;
}

.navbar-toggler-white .navbar-toggler-icon {
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%2833, 37, 41, 0.75%29' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e");
}

.btn-link.nav-link {
  color: #6c757d !important;
  text-decoration: none;
}

.btn-link.nav-link:hover {
  color: #0d6efd !important;
}

/* 响应式调整 */
@media (max-width: 991px) {
  .navbar-nav {
    padding-top: 1rem;
    border-top: 1px solid #dee2e6;
    margin-top: 1rem;
  }
  
  .nav-link {
    padding: 0.75rem 1rem;
    margin: 0.25rem 0;
  }
  
  .navbar-tools {
    margin-top: 1rem;
    padding-top: 1rem;
    border-top: 1px solid #dee2e6;
    justify-content: center;
  }
}

/* 动画效果 */
@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translateY(-30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.navbar {
  animation: fadeInDown 0.6s ease-out;
}

/* 用户下拉菜单样式 */
.dropdown-menu {
  border: none;
  border-radius: 0.75rem;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  min-width: 200px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.dropdown-header {
  color: #495057;
  font-weight: 600;
  border-bottom: 1px solid #dee2e6;
  padding: 0.75rem 1rem 0.5rem;
}

.dropdown-item {
  padding: 0.75rem 1rem;
  transition: all 0.3s ease;
  border-radius: 0.5rem;
  margin: 0.25rem 0.5rem;
}

.dropdown-item:hover {
  background-color: rgba(13, 110, 253, 0.1);
  color: #0d6efd;
  transform: translateX(5px);
}

.dropdown-item.text-danger:hover {
  background-color: rgba(220, 53, 69, 0.1);
  color: #dc3545;
}

.dropdown-divider {
  margin: 0.5rem 0;
  border-color: rgba(0, 0, 0, 0.1);
}

/* 登录按钮样式 */
.btn-outline-primary {
  border-radius: 0.5rem;
  font-weight: 500;
  transition: all 0.3s ease;
}

.btn-outline-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(13, 110, 253, 0.3);
}

/* 深色主题下的下拉菜单 */
.dark-theme .dropdown-menu,
[data-theme="dark"] .dropdown-menu {
  background: rgba(33, 37, 41, 0.95);
}

.dark-theme .dropdown-header,
[data-theme="dark"] .dropdown-header {
  color: #f8f9fa;
  border-color: rgba(255, 255, 255, 0.1);
}

.dark-theme .dropdown-item,
[data-theme="dark"] .dropdown-item {
  color: #f8f9fa;
}

.dark-theme .dropdown-item:hover,
[data-theme="dark"] .dropdown-item:hover {
  background-color: rgba(102, 179, 255, 0.2);
  color: #66b3ff;
}

.dark-theme .dropdown-item.text-danger:hover,
[data-theme="dark"] .dropdown-item.text-danger:hover {
  background-color: rgba(220, 53, 69, 0.2);
  color: #dc3545;
}

.dark-theme .dropdown-divider,
[data-theme="dark"] .dropdown-divider {
  border-color: rgba(255, 255, 255, 0.1);
}
</style>
